<template>
  <div :style="{ backgroundColor: '#fff', height: 'calc(100vh - 89px)' }">
    <div v-if="question" :style="{ display: 'flex', flex: 1, flexBasis: 'auto' }">
      <QuestionView v-bind="{ ID, question }" v-if="question.type === '代码'"></QuestionView>
      <questionselect v-bind="{ question, questionindex }" v-else>
        <matchfooter v-bind="{ index: ID, questionlist, ID }"></matchfooter>
      </questionselect>
    </div>
    <div v-else class="container" v-show="show">
      <div class="row">
        <div class="col text-center">
          <div>
            <el-alert :title="errormsg" type="error" effect="dark" center :closable="false" class="el-alert"
              show-icon />
          </div>
          <img class="img"
            src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/pic_timuzanshibukechakan.png" alt="">

        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncgetquestion, asyncgetquestionbank, Iobj } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { markdownhtml } from "../../../util/htmlstring";
import matchfooter from "./matchfooter.vue";
import QuestionView from "./question.vue";
import questionselect from "./questionselect.vue";

const p = defineProps<{ ID: number }>()

const question = ref<Studycodemodel.Iquestion>();
const questionbank = ref<Studycodemodel.Iquestionbank>();
const store = useStore(Storekey);
const router = useRouter()
const route = useRoute();

const show = ref(false)
const getquestion = computed(() => {
  return store.getters.getquestion;
});

const errormsg = ref('')
const getMyPractiseQuestion = computed(() => {
  return store.getters.getMyPractiseQuestion;
});
const questionindex = computed(() => {
  if (questionbankid.value) {
    const index = questionlist.value.findIndex((v) => {
      if (v) {
        return v.ID == p.ID;
      }
      return 0;
    });
    return index + 1;
  }
  return p.ID;
});
// 题目列表
const questionlist = computed<Studycodemodel.Iquestion[]>(() => {
  const questions: Studycodemodel.Iquestion[] = []
  if (questionbankid.value) {
    const x = questionbank.value?.questionquestionbank?.map((v) => v.question);
    if (x) {
      x.forEach(e => {
        if (e) {
          questions.push(e)
        }
      })
    };
    return questions;
  } else if (userId.value) {
    return getMyPractiseQuestion.value
  }
  return getquestion.value;
});
const routeQuery = computed(() => {
  return route.query as Record<string, string>
})
const order = computed(() => {
  return (routeQuery.value.order || 'ID') as string as keyof Studycodemodel.Iquestion
})
const offset = computed(() => {
  return Number(routeQuery.value.offset) || 0
})
const limit = computed(() => {
  return Number(routeQuery.value.limit) || 20
})
const sortable = computed(() => {
  return (routeQuery.value.sortable || 'ASC') as "DESC" | "ASC"
})
const range = computed(() => {
  return routeQuery.value.range || 'public' as string
})
const teamid = computed(() => {
  return Number(routeQuery.value.teamid) || null
})
const questionbankid = computed(() => {
  return routeQuery.value.questionbankid as unknown as number | undefined;
});
const userId = computed(() => {
  return routeQuery.value.userId as unknown as number | undefined;
});

const formInline = reactive<{ teamid: number | undefined, name: string | number, }>(Object.assign({
  teamid: undefined,
  name: "",
}, routeQuery.value))

async function getQuestionList() {
  if (questionbankid.value) {
    const data = await asyncgetquestionbank({
      ID: Number(questionbankid.value)
    })
    questionbank.value = data
  }
  // 最近练习-成员练习题单
  else if (userId.value) {
    await store.dispatch("actionMyPractiseQuestion", {
      userid: Number(userId.value),
      _order: "questionid",
      _sortable: "DESC",
    });
  }
  else {
    const { name, teamid } = formInline;
    const obj: Iobj<Studycodemodel.Iquestion> = {
      _order: order.value,
      _sortable: sortable.value,
      _offset: offset.value,
      _limit: limit.value,
    };
    let _like: [keyof Studycodemodel.Iquestion, any]
    if (name) {
      _like = ["name", formInline.name];
      const id = Number(name);
      if (id == name) {
        _like = ["ID", id];
      }
      obj._like = _like;
    }
    if (formInline.ID) {
      obj.ID = formInline.ID
    }
    if (range.value) {
      obj.range = range.value
    }
    if (formInline.jobid) {
      (obj as any).jobid = formInline.jobid
    }
    if (formInline.activityid) {
      (obj as any).activityid = formInline.activityid
    }
    if (formInline.ismatch) {
      (obj as any).ismatch = formInline.ismatch
    }
    // 
    if (formInline.teamid) {
      obj.teamid = formInline.teamid
    }
    if (formInline.userid) {
      obj.userid = formInline.userid
    }
    if (formInline.rating) {
      obj.rating = formInline.rating
    }
    if (formInline.source) {
      obj.source = formInline.source
    }
    if (Array.isArray(formInline.difficulty) && formInline.difficulty.length) {
      obj.difficulty = formInline.difficulty
    }
    if (formInline.setlabel && formInline.setlabel.length) {
      if (!obj._include) obj._include = {};
      obj._include.questionlabel = ["labelid", formInline.setlabel];
    }
    await store.dispatch("actionquestion", obj);
  }
}

const ids = ref<number[]>()

onMounted(async () => {
  getQuestion(p.ID);
  getQuestionList()
})

async function getQuestion(ID: number) {
  try {
    const e = await asyncgetquestion({
      ID, questionbankid: questionbankid.value, user: true
    });
    question.value = markdownhtml(e) as Studycodemodel.Iquestion
    show.value = false
  } catch (e) {
    question.value = undefined
    show.value = true
    errormsg.value = String(e)
  }
}

watch(() => p.ID, () => {
  if (p.ID) {
    getQuestion(p.ID);
  }
});
watch(offset, async () => {
  await getQuestionList();  // 等待新题目列表获取完成
  const query = { ...route.query };
  if (Boolean(query.showFirst)) {
    const newId = questionlist.value[0]?.ID;
    if (newId) {
      router.push({ params: { ID: newId }, query });  // 更新路由参数
    }
  }
});
onBeforeRouteUpdate(() => {
  // getQuestionList()
})
</script>

<style scoped>
.el-alert {
  background: #F5F5F5 !important;
  width: 640px !important;
  height: 52px;
  border: 1px solid rgba(0, 0, 0, 0.06) !important;
  border-radius: 4px !important;
  margin: 96px auto 60px auto !important;
  color: #000 !important;
  --el-alert-title-font-size: 16px !important;
}
</style>

<style>
.img {
  object-fit: cover;
  max-width: 640px;
}
</style>
